﻿/*
'Description:与三坐标集成
'Copyright (c) : 通力凯顿（北京）系统集成有限公司
'Writer:Wangjh 
'create Date:20230505
'Rewriter:
'Rewrite Date:
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using UFC.DBUtility;
using UFC.Common;
using System.Xml;
using System.Configuration;
using Newtonsoft.Json;
using System.IO;
using System.Collections;
using System.Text.RegularExpressions;

namespace SendIndustrialNetwork
{
    public class ThreeCoordinateCheck
    {
        private const string m_TempCommiType = "SendThreeCoordinate";//推送三坐标
        private static readonly string m_FilePath = ConfigurationManager.AppSettings["acceptFilePath"];//文件接收的位置
      private static readonly string m_BackFilePath = ConfigurationManager.AppSettings["backFilePath"];//文件备份的位置

      public void Excute()
      {
          LogHelp.SetConfig(); 
          try
          {
              SendData();//数据发送          
          }
          catch (Exception ex) {
              LogHelp.WriteError("推送给三坐标任务数据："+ex.Message ,ex);
          }

          try
          {
              DealReciveData(); //处理异步返回的消息     
          }
          catch (Exception ex) {
              LogHelp.WriteError("接收三坐标数据："+ex.Message ,ex);
          }
          
      }

        /// <summary>
        /// 接收后数据处理
        /// </summary>
        void DealReciveData()
        {
            var dirs = new DirectoryInfo(m_FilePath);
            foreach (FileInfo fi in dirs.GetFiles())
            {
                if (fi.Extension.Replace(".", "").ToLower() != "txt")
                    continue;
                //解析并判断业务
                XmlDocument myxml = new XmlDocument();
                myxml.Load(fi.FullName);   
              //获取业务方法验证
              if (myxml.SelectSingleNode("root/header/BusinessFun") == null)
              {
                  continue;
              }
              var businessFun = myxml.SelectSingleNode("root/header/BusinessFun").InnerText;
              try
              {
                  switch (businessFun)
                  {
                      case "ReciveSZBCheckItemResult":
                          ReciveSZBCheckItemResult(myxml, fi);//处理三坐标尺寸的结果信息
                          break;
                      case "SendCheckItemToSZB_ResMsg"://处理MES给三坐标的尺寸信息后，三坐标返回接收成功/失败的消息
                          SendCheckItemToSZB_ResMsg(myxml, fi);
                          break;
                      default:
                          break;

                  }
              }
              catch (Exception ex) {
                  LogHelp.WriteOrcale("MES接收三坐标结果_处理异常" + "@^" + ex.Message + "@^" + fi.Name + " " + myxml.InnerXml + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + "");
                  LYIndustryFileExchangeHelper.MoveBackFile(fi, "");
              }
            }
        }

        /// <summary>
        /// 三坐标返回信息，发送给三坐标任务
        /// </summary>
        /// <param name="myxml"></param>
        /// <param name="fi"></param>
        void SendCheckItemToSZB_ResMsg(XmlDocument myxml, FileInfo fi)
        {
            string id2 = myxml.SelectSingleNode("root/document/InspectID").InnerText;
            var isSuccess = myxml.SelectSingleNode("root/document/isSuccess").InnerText == "true" ? "0" : "1";
            string msg = myxml.SelectSingleNode("root/document/msg").InnerText;

            OracleHelper.ExecuteSql(string.Format("writetoothersystem wt set wt.issuccess='{0}',wt.resxml=wt.resxml||'{1}' where wt.parentid='{2}' ",
                isSuccess, " " + myxml.OuterXml.Replace("\n", "").Replace("\r", "").Trim(' '), id2));
            LYIndustryFileExchangeHelper.MoveBackFile(fi, "");
        }

        /// <summary>
        /// 处理三坐标尺寸结果信息
        /// </summary>
        /// <param name="myxml"></param>
        /// <param name="fi"></param>
        void ReciveSZBCheckItemResult(XmlDocument myxml, FileInfo fi)
        {
            //业务实际处理
            string id2 = myxml.SelectSingleNode("root/document/TaskInfo/InspectID").InnerText;
            LogHelp.WriteOrcale("MES接收三坐标结果_处理日志" + "@^" + "开始处理:" + fi.Name + "@^" + myxml.InnerXml + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + id2);

            var sendDt = OracleHelper.Query("select * from SendThreeCoordinateRecord where id2='" + id2 + "'").Tables[0];//发送的信息
            if (sendDt.Rows.Count == 0)
            {//未找到此任务

                WriteLogAndSendExchange(fi, "CMMRESULT_RECEIVE", "false", "MES中未找到此任务,对应字段：InspectID", id2, "MES处理三坐标结果的返回信息", "mes_app", "MES接收三坐标结果_处理日志");
                return;
            }

            var checkItemResults = myxml.SelectSingleNode("root/document/DimensionList");
            if (checkItemResults == null)
            {//无DimensionList节点信息

                WriteLogAndSendExchange(fi, "CMMRESULT_RECEIVE", "false", "XML结构中无DimensionList节点信息", id2, "MES处理三坐标结果的返回信息", "mes_app", "MES接收三坐标结果_处理日志");
                return;
            }

            //          string childNo = myxml.SelectSingleNode("root/document/TaskInfo/sn").InnerText;//子序号编号
            //          DataTable childContainerDt = new DataTable();
            //          if (!string.IsNullOrWhiteSpace(childNo))
            //          {
            //              childContainerDt = OracleHelper.Query(string.Format(@"select c.containername,c.containerid from container c
            //where c.status=1 and c.parentcontainerid='{0}' and c.qualificationnum in ({1})", sendDt.Rows[0]["containerid"].ToString(), "'" + childNo.Replace(",","','") + "'")).Tables[0];
            //              if (childContainerDt.Rows.Count == 0)
            //              {
            //                  WriteLogAndSendExchange(fi, "CMMRESULT_RECEIVE", "false", "MES中未找到此子序号,对应字段：sn", id2, "MES处理三坐标结果的返回信息", "mes_app", "MES接收三坐标结果_处理日志");
            //                  return;                   
            //              }
            //          }

            var sqlList = new ArrayList();
            foreach (XmlNode checkItem in checkItemResults.ChildNodes)
            {
                string childNo = checkItem.SelectSingleNode("sn").InnerText;//子序号编号
                DataTable childContainerDt = new DataTable();
                if(!string.IsNullOrWhiteSpace(childNo)){
                     childContainerDt = OracleHelper.Query(string.Format(@"select c.containername,c.containerid from container c
                                where c.status=1 and c.parentcontainerid='{0}' and c.qualificationnum in ({1})", sendDt.Rows[0]["containerid"].ToString(), "'" + childNo.Replace(",", "','") + "'")).Tables[0];
                    if (childContainerDt.Rows.Count == 0)
                    {
                        WriteLogAndSendExchange(fi, "CMMRESULT_RECEIVE", "false", "MES中未找到此子序号,对应字段：sn", id2, "MES处理三坐标结果的返回信息", "mes_app", "MES接收三坐标结果_处理日志");
                        return;
                    }
                }
                var emp = checkItem.SelectSingleNode("measured_user").InnerText;//员工号
                var employeeid = OracleHelper.GetSingle("select employeeid from employee where employeename='" + emp + "'");
                if (employeeid == null)
                {
                    WriteLogAndSendExchange(fi, "CMMRESULT_RECEIVE", "false", "MES中未找到此人员，字段：measured_user", id2, "MES处理三坐标结果的返回信息", "mes_app", "MES接收三坐标结果_处理日志");
                    return;
                }
                var result = checkItem.SelectSingleNode("measured_value").InnerText;
                if (string.IsNullOrWhiteSpace(result))
                {
                    WriteLogAndSendExchange(fi, "CMMRESULT_RECEIVE", "false", "测量结果不能为空，字段：measured_value", id2, "MES处理三坐标结果的返回信息", "mes_app", "MES接收三坐标结果_处理日志");
                    return;
                }
                var createDate = checkItem.SelectSingleNode("measured_time").InnerText;
                if (IsDateTime(createDate) == false)
                {
                    WriteLogAndSendExchange(fi, "CMMRESULT_RECEIVE", "false", "日期格式错误，字段：measured_time", id2, "MES处理三坐标结果的返回信息", "mes_app", "MES接收三坐标结果_处理日志");
                    return;
                }
                var stepCheckPointId = checkItem.SelectSingleNode("checkItemID").InnerText;
                var thisItemSend = sendDt.Select("stepCheckPointId='" + stepCheckPointId + "'");
                if (thisItemSend.Length == 0)
                {
                    WriteLogAndSendExchange(fi, "CMMRESULT_RECEIVE", "false", "MESMES中未找到此检测尺寸，字段：checkItemID", id2, "MES处理三坐标结果的返回信息", "mes_app", "MES接收三坐标结果_处理日志");
                    return;
                }

                GetSaveCheckResultSql(thisItemSend[0], childContainerDt, employeeid.ToString(), createDate, result, ref sqlList);
            }

            OracleHelper.ExecuteSqlTran(sqlList);

            //处理成功，返回消息
            WriteLogAndSendExchange(fi, "CMMRESULT_RECEIVE", "true", "MES接收三坐标结果成功", id2, "MES处理三坐标结果的返回信息", "mes_app", "MES接收三坐标结果_处理日志");

            //returnMsg = ReturnMessage("CMMRESULT_RECEIVE", "true", "MES接收三坐标结果成功", id2);
            //LogHelp.WriteLog(returnMsg);
            //string msg=  LYIndustryFileExchangeHelper.FileUpload("11012", "MES处理三坐标结果的返回信息", returnMsg, "");//文件推送给数据交换系统
            //string code = "";
            //if (!string.IsNullOrWhiteSpace(msg))
            //{
            //    var reMsgObj = JsonConvert.DeserializeObject<Dictionary<string, string>>(msg);
            //    code = reMsgObj["code"];
            //    LYIndustryFileExchangeHelper.SendSysLogByUDP(code,"mes_admin", "MES处理三坐标结果的返回信息", "xml", returnMsg.Length.ToString(), "");
            //}
            //LYIndustryFileExchangeHelper.MoveBackFile(fi, "");
            //LogHelp.WriteOrcale("ReciveSZBCheckItemResult_三坐标结果信息" + "@^" + returnMsg + "@^" + fi.Name + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + id2);
        }

        /// <summary>
        /// 保存的sql
        /// </summary>
        /// <param name="sendItem"></param>
        /// <param name="childConDt"></param>
        /// <param name="employeeid"></param>
        /// <param name="createDate"></param>
        /// <returns></returns>
        void GetSaveCheckResultSql(DataRow sendItem, DataTable childConDt, string employeeid, string createDate, string result, ref ArrayList sqlList)
        {
            DataTable existDt = OracleHelper.Query(string.Format(@"select * from stepcheckpointresult sr where sr.containerid='{0}'  and sr.stepcheckpointid='{1}'",
                sendItem["containerid"].ToString(), sendItem["STEPCHECKPOINTID"].ToString())).Tables[0];

            string updateSql = @"update STEPCHECKPOINTRESULT sr set sr.workerid='{0}',sr.workcheckpointresultnote='{1}',sr.workcheckpointresultnotedis='{2}',
sr.createdate=to_date('{3}','yyyy/mm/dd hh24:mi:ss'),sr.tempdealfail=0,lastchangedate=sysdate where sr.stepcheckpointresultid='{4}'";

            string insertSql = @"INSERT INTO STEPCHECKPOINTRESULT (lastchangedate,WORKERID,WORKCHECKPOINTRESULTNOTE,WORKCHECKPOINTRESULTNOTEDIS,CONTAINERID,ChildContainerID,CREATEDATE,FACTORYID,STEPCHECKPOINTID,
STEPCHECKPOINTRESULTID,containerstepworkreportid) VALUES (sysdate,'{0}','{1}','{2}','{3}','{4}',to_date('{5}','yyyy/mm/dd hh24:mi:ss'),'{6}','{7}','{8}','{9}')";

            //查询自动报工情况，没有派工记录
            DataTable autoReportDt = OracleHelper.Query(string.Format(@"SELECT csw.containerstepworkreportid FROM containerstepworkreport csw WHERE csw.containerid='{0}' AND csw.workflowstepid='{1}' AND csw.isuse=0 AND csw.containerstepdispatchid IS NULL", sendItem["containerid"].ToString(), sendItem["workflowstepid"].ToString())).Tables[0];
            string reportId = "";
            if (autoReportDt.Rows.Count > 0) {
                reportId = autoReportDt.Rows[0]["containerstepworkreportid"].ToString();
            }

            if (childConDt.Rows.Count > 0)
            {
                foreach (DataRow childRow in childConDt.Rows)
                {
                    var childCheckItem = existDt.Select("ChildContainerID='" + childRow["containerid"].ToString() + "'");
                    if (childCheckItem.Length > 0)
                    {
                        sqlList.Add(string.Format(updateSql, employeeid, result, result, createDate, childCheckItem[0]["stepcheckpointresultid"].ToString()));
                    }
                    else
                    {

                        sqlList.Add(string.Format(insertSql, employeeid, result, result, sendItem["containerid"].ToString(), childRow["containerid"].ToString(), createDate,
                            sendItem["FACTORYID"].ToString(), sendItem["STEPCHECKPOINTID"].ToString(), Guid.NewGuid().ToString(), reportId));
                    }
                }
            }
            else
            {
                if (existDt.Rows.Count > 0)
                {
                    sqlList.Add(string.Format(updateSql, employeeid, result, result, createDate, existDt.Rows[0]["stepcheckpointresultid"].ToString()));
                }
                else
                { 
                    sqlList.Add(string.Format(insertSql, employeeid, result, result, sendItem["containerid"].ToString(), "", createDate,
                             sendItem["FACTORYID"].ToString(), sendItem["STEPCHECKPOINTID"].ToString(), Guid.NewGuid().ToString(), reportId));
                }
            }
        }

        /// <summary>
        /// 日期验证
        /// </summary>
        /// <param name="StrSource"></param>
        /// <returns></returns>
        public bool IsDateTime(string StrSource)
        {
            return Regex.IsMatch(StrSource, @"^(((((1[6-9]|[2-9]\d)\d{2})-(0?[13578]|1[02])-(0?[1-9]|[12]\d|3[01]))|(((1[6-9]|[2-9]\d)\d{2})-(0?[13456789]|1[012])-(0?[1-9]|[12]\d|30))|(((1[6-9]|[2-9]\d)\d{2})-0?2-(0?[1-9]|1\d|2[0-8]))|(((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))-0?2-29-)) (20|21|22|23|[0-1]?\d):[0-5]?\d:[0-5]?\d)$");
        }


        /// <summary>
        /// 返回消息生成
        /// </summary>
        /// <param name="toAppFun"></param>
        /// <param name="isSuccess"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        string ReturnMessage(string toAppFun, string isSuccess, string msg, string id)
        {
            string str = string.Format(@"<?xml version=""1.0"" encoding=""UTF-8""?><root><header><BusinessFun>{0}</BusinessFun></header><document><InspectID>{3}</InspectID><isSuccess>{1}</isSuccess><msg>{2}</msg></document></root>",
                toAppFun, isSuccess, msg, id);

            return str;
        }

        /// <summary>
        /// 数据发送处理
        /// </summary>
        public void SendData()
        {
            //获取需要推送的数据
            DataTable mainDt = GetNeedDealData();
            foreach (DataRow mainRow in mainDt.Rows)
            {
                //循环数据生成指定格式
                DataTable checkItemDt = GetCheckItem(mainRow["id2"].ToString());
                var requestXml = CreateXML(mainRow, checkItemDt);
                //调用
                LogHelp.WriteLog("推送三坐标系统XML：" + requestXml.OuterXml);

              #region 临时测试用，无误后取消
              string fileName = "MES给三坐标检测系统任务" + ".xml";
              //requestXml.Save(m_BackFilePath+"\\" + fileName);
              #endregion

              string msg = LYIndustryFileExchangeHelper.FileUpload("11012", fileName, requestXml.OuterXml, "");//文件推送给数据交换系统
              string code = "";
              if (!string.IsNullOrWhiteSpace(msg))
              {
                  try
                  {
                      var reMsgObj = JsonConvert.DeserializeObject<Dictionary<string, string>>(msg);
                      code = reMsgObj["code"];
                      LYIndustryFileExchangeHelper.SendSysLogByUDP(code, mainRow["applyFullname"].ToString(), fileName, "xml", requestXml.OuterXml.Length.ToString(), "");
                  }
                  catch (Exception ex) {
                      WriteLogAndSendExchange(new FileInfo(""), "CMMTASK_RECEIVE", "false", msg, "", "MES推送三坐标返回信息Token失效", "mes_app", "MES接收三坐标结果_处理日志");
                      CacheHelper.SetToken("token_11012", string.Empty);
                      continue;
                  }
               }
              //推送完毕，更新业务数据，写入MES数据库日志
              UpdateSended(mainRow["id2"].ToString(), mainRow["containerid"].ToString(), mainRow["WorkflowStepId"].ToString());
              OracleDAL.InserOtherSystemRecord(new Dictionary<string, string>() { 
                 {"ParentId",mainRow ["id2"].ToString ()},{"RecordType",m_TempCommiType},
                        {"ContainerID",mainRow ["containerid"].ToString ()},{"ContainerName",mainRow ["containername"].ToString ()},{"IsSuccess",code=="200"?"0":"1"},
                        {"ProductName",mainRow ["productname"].ToString ()},{"WorkflowStepName",mainRow ["workflowstepname"].ToString ()},
                        {"SendXml",requestXml.OuterXml},{"ResXml",msg}
            });
            }
        }

      /// <summary>
      /// 获取待处理的主数据
      /// </summary>
      /// <returns></returns>
      DataTable GetNeedDealData() {
          string strSql = @"SELECT sc.isuse,w.process_no,cci.familylistnames,w.Part_RevID,w.ly2sequence,cci.productname,cci.productdescription,ut.attributevalue PARTWORKWHOP,
cci.workflowrevision,p.materialcode,w.workflowtype2,s.specno,s.opdesc,ut2.attributevalue WorkShop,st.spectypename,s.iskey,
cci.realcontainerno,cci.qty wipqty,sc.qty,wm_concat(distinct c.qualificationnum) childNo,sc.containerstepdispatchid,e.fullname applyFullname,e.employeename applyname,sc.applyfactorycode,
sc.id2,cci.containerid,cci.containername,cci.workflowstepname,sc.WorkflowStepId FROM SendThreeCoordinateRecord sc
left join employee e on e.employeeid=sc.createemployeeid
left join containercurrentinfo cci on cci.containerid=sc.containerid and cci.WorkflowStepId=sc.WorkflowStepId
left join product p on p.productid=cci.productid
left join workflow w on w.workflowid=cci.workflowid
left join spec s on s.specid=cci.specid
left join spectype st on st.spectypeid=s.spectypeid
left join userattribute ut on ut.parentid=cci.originalfactoryid and ut.userattributename='分厂代码'
left join userattribute ut2 on ut2.parentid=s.factoryid and ut2.userattributename='分厂代码' 
left join container c on c.parentcontainerid=cci.containerid and c.status=1
where sc.issend=0 and cci.containerstatus=1 and cci.isinstore=0 and rownum<101
group by w.process_no,cci.familylistnames,w.Part_RevID,w.ly2sequence,cci.productname,cci.productdescription,ut.attributevalue,
cci.workflowrevision,p.materialcode,w.workflowtype2,s.specno,s.opdesc,ut2.attributevalue,st.spectypename,s.iskey,e.employeename,sc.WorkflowStepId,
cci.realcontainerno,cci.qty,sc.qty,sc.containerstepdispatchid,sc.isuse,sc.applyfactorycode,e.fullname,sc.id2,cci.containerid,cci.containername,cci.workflowstepname";
            return OracleHelper.Query(strSql).Tables[0];
        }

        /// <summary>
        /// 获取检测项详细信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        DataTable GetCheckItem(string id2)
        {
            string strSql = string.Format(@"SELECT st.BubbleNumber,st.name,st.spctype,st.BaseValue,st.FloorFloat,st.CeilFloat,sc.stepcheckpointid,nvl2(st.TCcheckpointnote,'工艺委托','临时委托') CommissionedType FROM SendThreeCoordinateRecord sc
inner join stepcheckpoint st on st.stepcheckpointid=sc.stepcheckpointid

where sc.id2='{0}' ORDER BY ST.CHECKNO ", id2);
            return OracleHelper.Query(strSql).Tables[0];
        }

        /// <summary>
        /// 业务数据推送更新
        /// </summary>
        /// <param name="id2"></param>
        void UpdateSended(string id2, string containerId, string stepId)
        {
            OracleHelper.ExecuteSql(string.Format(@"update SendThreeCoordinateRecord set issend=1 where id2='{0}' and containerId='{1}' and WorkflowStepId='{2}' ",
                id2, containerId, stepId));
        }

        /// <summary>
        /// 生成xml结构
        /// </summary>
        /// <param name="dr"></param>
        /// <returns></returns>
        XmlDocument CreateXML(DataRow dr, DataTable checkItemDt)
        {
            XmlDocument doc = new XmlDocument();
            doc.AppendChild(doc.CreateXmlDeclaration("1.0", "utf-8", ""));
            XmlNode root = doc.CreateElement("root");
            root.AppendChild(doc.CreateElement("header"));

            root.LastChild.AppendChild(doc.CreateElement("BusinessFun"));
            root.LastChild.LastChild.InnerText = "CMMTASK_RECEIVE";//三坐标的业务方法,待定

            XmlNode document = doc.CreateElement("document");//业务主体
            //填充PartInfo
            document.AppendChild(doc.CreateElement("PartInfo"));

            document.LastChild.AppendChild(doc.CreateElement("CraftNo"));//工艺规程
            document.LastChild.LastChild.InnerText = dr["process_no"].ToString();

            document.LastChild.AppendChild(doc.CreateElement("part_rev"));
            document.LastChild.LastChild.InnerText = dr["familylistnames"].ToString();

            document.LastChild.AppendChild(doc.CreateElement("part_code"));
            document.LastChild.LastChild.InnerText = dr["productname"].ToString();

            document.LastChild.AppendChild(doc.CreateElement("part_name"));
            document.LastChild.LastChild.InnerText = dr["productdescription"].ToString();

            document.LastChild.AppendChild(doc.CreateElement("PartStage"));
            document.LastChild.LastChild.InnerText = dr["Part_RevID"].ToString();

            document.LastChild.AppendChild(doc.CreateElement("PARTWORKWHOP"));
            document.LastChild.LastChild.InnerText = dr["PARTWORKWHOP"].ToString();

            document.LastChild.AppendChild(doc.CreateElement("PartVer"));
            document.LastChild.LastChild.InnerText = dr["ly2sequence"].ToString();

            document.LastChild.AppendChild(doc.CreateElement("CraftRoute"));
            document.LastChild.LastChild.InnerText = dr["workflowrevision"].ToString();

            document.LastChild.AppendChild(doc.CreateElement("PartDrawingCode"));
            document.LastChild.LastChild.InnerText = dr["materialcode"].ToString();

            document.LastChild.AppendChild(doc.CreateElement("IsTemp"));
            document.LastChild.LastChild.InnerText = dr["workflowtype2"].ToString();

            document.LastChild.AppendChild(doc.CreateElement("OPLabel"));
            document.LastChild.LastChild.InnerText = dr["specno"].ToString();

            document.LastChild.AppendChild(doc.CreateElement("OPName"));
            document.LastChild.LastChild.InnerText = dr["opdesc"].ToString();

            document.LastChild.AppendChild(doc.CreateElement("WorkShop"));
            document.LastChild.LastChild.InnerText = dr["WorkShop"].ToString();

            document.LastChild.AppendChild(doc.CreateElement("ProcessType"));
            document.LastChild.LastChild.InnerText = dr["spectypename"].ToString();

            document.LastChild.AppendChild(doc.CreateElement("IsKeyOP"));
            document.LastChild.LastChild.InnerText = dr["iskey"].ToString();

            //填充 TaskInfo
            document.AppendChild(doc.CreateElement("TaskInfo"));

            document.LastChild.AppendChild(doc.CreateElement("batch_code"));
            document.LastChild.LastChild.InnerText = dr["realcontainerno"].ToString();

            document.LastChild.AppendChild(doc.CreateElement("batch_no"));
            document.LastChild.LastChild.InnerText = dr["qty"].ToString();

            document.LastChild.AppendChild(doc.CreateElement("sn"));
            document.LastChild.LastChild.InnerText = dr["childNo"].ToString();

            document.LastChild.AppendChild(doc.CreateElement("InspectID"));
            document.LastChild.LastChild.InnerText = dr["id2"].ToString();

            document.LastChild.AppendChild(doc.CreateElement("CreationTime"));
            document.LastChild.LastChild.InnerText = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

            document.LastChild.AppendChild(doc.CreateElement("operator"));
            document.LastChild.LastChild.InnerText = dr["applyname"].ToString();

            document.LastChild.AppendChild(doc.CreateElement("CommissionedWrokshop"));
            document.LastChild.LastChild.InnerText = dr["applyfactorycode"].ToString();

            //填充DimensionList
            XmlNode DimensionList = doc.CreateElement("DimensionList");

            foreach (DataRow checkItem in checkItemDt.Rows)
            {
                DimensionList.AppendChild(doc.CreateElement("Dimensions"));

                DimensionList.LastChild.AppendChild(doc.CreateElement("CommissionedType"));//委托计量类型
                DimensionList.LastChild.LastChild.InnerText = checkItem["CommissionedType"].ToString();

                DimensionList.LastChild.AppendChild(doc.CreateElement("dimension_no"));//气泡号
                DimensionList.LastChild.LastChild.InnerText = checkItem["BubbleNumber"].ToString();

                DimensionList.LastChild.AppendChild(doc.CreateElement("dimension_flag"));//关重符号/检测项名称
                DimensionList.LastChild.LastChild.InnerText = checkItem["name"].ToString();

                //DimensionList.LastChild.AppendChild(doc.CreateElement("DimensionalType"));//尺寸特性,定性或定量，目前tc未推
                //DimensionList.LastChild.LastChild.InnerText = dr["DimensionalType"].ToString();

                DimensionList.LastChild.AppendChild(doc.CreateElement("nominal"));//基准值
                DimensionList.LastChild.LastChild.InnerText = checkItem["BaseValue"].ToString();

                DimensionList.LastChild.AppendChild(doc.CreateElement("upper_tol"));//上公差
                DimensionList.LastChild.LastChild.InnerText = checkItem["FloorFloat"].ToString();

                DimensionList.LastChild.AppendChild(doc.CreateElement("lower_tol"));//下公差
                DimensionList.LastChild.LastChild.InnerText = checkItem["CeilFloat"].ToString();

                DimensionList.LastChild.AppendChild(doc.CreateElement("checkItemID"));//mesID
                DimensionList.LastChild.LastChild.InnerText = checkItem["stepcheckpointid"].ToString();

            }

            document.AppendChild(DimensionList);

            root.AppendChild(document);
            doc.AppendChild(root);

            return doc;
        }

        /// <summary>
        /// 日志写入，包含文本日志，数据库日志，给日志系统的日志，给对方业务系统的日志
        /// </summary>
        /// <param name="fi">发生日志的文件</param>
        /// <param name="businessFun">给对方业务系统的日志，对方的业务方法</param>
        /// <param name="isSuccess">true/false</param>
        /// <param name="reqMsg">日志描述</param>
        /// <param name="mainId">业务数据主id</param>
        /// <param name="sendFileName">给日志系统的日志，给对方业务系统的日志的文件名</param>
        /// <param name="operater">操作者</param>
        /// <param name="logMark">文本日志，数据库日志的标记</param>
        void WriteLogAndSendExchange(FileInfo fi, string businessFun, string isSuccess, string reqMsg, string mainId, string sendFileName, string operater, string logMark)
        {
            string returnMsg = ReturnMessage(businessFun, isSuccess, reqMsg, mainId);
            LogHelp.WriteLog(logMark + returnMsg);
            string msg = LYIndustryFileExchangeHelper.FileUpload("11012", sendFileName + ".xml", returnMsg, "");//文件推送给数据交换系统
            string code = "";
            if (!string.IsNullOrWhiteSpace(msg))
            {
                var reMsgObj = JsonConvert.DeserializeObject<Dictionary<string, string>>(msg);
                code = reMsgObj["code"];
                LYIndustryFileExchangeHelper.SendSysLogByUDP(code, operater, sendFileName + ".xml", "xml", returnMsg.Length.ToString(), "");
            }
            LYIndustryFileExchangeHelper.MoveBackFile(fi, "");
            LogHelp.WriteOrcale(logMark + "@^" + fi.Name + "@^" + returnMsg + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + mainId);
        }
    }
}
